package server;

import java.io.*;
import java.net.Socket;
import java.util.List;

import com.sun.net.ssl.internal.www.protocol.https.Handler;

public class ChatServiceHandler implements Runnable {
	private Socket s;
	private PrintWriter out = null;
	private List<ChatServiceHandler> handlers;
		//本处理器有一个属性，是他自己的集合。换句话说，这个处理器对象实际上就是一个处理器集合.
	public ChatServiceHandler(Socket s) {
		super();
		this.s = s;
	}


	public List<ChatServiceHandler> getHandlers() {
		return handlers;
	}

	public void setHandlers(List<ChatServiceHandler> handlers) {
		this.handlers = handlers;
	}
	
	public void run() {
		BufferedReader in = null;
		try {
			in = new BufferedReader(
					new InputStreamReader(
							s.getInputStream()));
			out = new PrintWriter(
					  new OutputStreamWriter(
							s.getOutputStream()));
			while (true) {
				String req = in.readLine();
				System.out.println("get = " +req);
				sendAll(req);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				s.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void sendAll(String message){
		for(ChatServiceHandler h : handlers){
			h.send(message);
		}
	}
	
	private void send(String message){
		try {
		   out.println(message);
		   out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}